<?php

namespace App\Http\Controllers;

use App\Models\Address;
use Illuminate\Support\Facades\Input;

class AddressController extends WxBaseController
{
    public function list(){
        $list = Address::where('wxuser_id',$this->auth()->id)->get();
        return $this->apiReturn(true,'success',$list);
    }
    public function default($id){
        $address = Address::find($id);
        if(count($address)>0&&!empty($address)){
            $bool = $address->setDefault($this->auth()->id);
            if($bool)
                return $this->apiReturn(true,'success',Address::where('wxuser_id',$this->auth()->id)->get());
            else
                return $this->apiReturn(false,$id.'已经为默认');
        }else{
            return $this->apiReturn(false,'该用户不存在此地址,请检查ID是否正确');
        }
    }
    public function detail($id){
        return $this->apiReturn(true,'success',Address::find($id));
    }
    public function add(){
        $input = request();
        $params = [
            'name'=>$input->name,
            'wxuser_id'=>$this->auth()->id,
            'phone'=>$input->phone,
            "area"=> $input->area,
            "detail"=>$input->detail
        ];
        $adr = Address::where('wxuser_id',$this->auth()->id)->first();
        $params['default']=$adr?0:1;
        $address = Address::updateOrCreate(['id'=>$input->id],$params);
        //$address->default($this->auth()->id,$input->default);
        return $this->apiReturn(true,'success',Address::all());
    }

    public function delete($id){
        return $this->apiReturn(true,'success',Address::destroy($id));
    }
}